package com.kexilo.core.common.interceptor;

import com.alibaba.fastjson2.JSON;
import com.kexilo.core.common.annotation.RepeatSubmit;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交拦截器
 *
 * @author Kexilo
 */
@Component
public class RepeatSubmitInterceptor implements HandlerInterceptor {
    
    private static final Logger log = LoggerFactory.getLogger(RepeatSubmitInterceptor.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null) {
                if (this.isRepeatSubmit(request, annotation)) {
                    R<Object> ajaxResult = R.error("不允许重复提交，请稍候再试");
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @return
     * @throws Exception
     */
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) throws Exception {
        String nowParams = buildRepeatSubmitKey(request);

        // 唯一标识（指定key + url + 消息头）
        String submitKey = annotation.key() + request.getRequestURI();

        // 唯一标识（指定key + url + 消息头）
        submitKey = submitKey + ":" + nowParams;

        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        if (ops.get(submitKey) == null) {
            ops.set(submitKey, "", annotation.interval(), TimeUnit.MILLISECONDS);
            return false;
        }
        return true;
    }

    /**
     * 构建重复提交key
     *
     * @param request
     * @return
     */
    private String buildRepeatSubmitKey(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        String params = "";
        try {
            params = ServletUtils.getBodyString(request);
        } catch (IOException e) {
            log.error("读取请求参数异常", e);
        }
        sb.append(request.getRequestURI()).append("_");
        sb.append(params);
        return sb.toString();
    }
}
